package com.entfrm.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.entfrm.base.api.R;
import com.entfrm.base.config.GlobalConfig;
import com.entfrm.security.entity.EntfrmUser;
import com.entfrm.security.util.SecurityUtil;
import com.entfrm.system.entity.*;
import com.entfrm.system.service.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping( "/contract")
public class ContractMangeController {
    private final ContractMangeService contractMangeService;
    private final DeptService deptService;

    private final ContractPlanService contractPlanService;
    private QueryWrapper<ContractManage> getQueryWrapper(ContractManage contractManage) {
        return new QueryWrapper<ContractManage>()
                .like(StrUtil.isNotBlank(contractManage.getContractName()), "contract_name", contractManage.getContractName())
                .like(StrUtil.isNotBlank(contractManage.getContractSn()), "contract_sn", contractManage.getContractSn())
                .eq(StrUtil.isNotBlank(contractManage.getDeptId()),"dept_id",contractManage.getDeptId())
                .in(contractManage.getSelDept().size()>0,"dept_id",contractManage.getSelDept())
                .like(StrUtil.isNotBlank(contractManage.getContractFactory()), "contract_factory", contractManage.getContractFactory())
                .between(StrUtil.isNotBlank(contractManage.getStartTime()) && StrUtil.isNotBlank(contractManage.getEndTime()), "create_time", contractManage.getStartTime(), contractManage.getEndTime()).orderByDesc("create_time");
    }
    private QueryWrapper<ContractPlan> getQueryWrapper(ContractPlan contractPlan) {
        return new QueryWrapper<ContractPlan>()
                .eq(StrUtil.isNotBlank(contractPlan.getContractId()), "contract_id", contractPlan.getContractId());

    }

    @PostMapping("/updateHt")
    public R updateHt(ContractManage contractManage) {
        contractMangeService.updateById(contractManage);
        return R.ok();
    }
    @GetMapping("/getCountByYear")
    public R getCountByYear() {
        List<ContractManage> list=contractMangeService.getContractByYear();
        return R.ok(list, list.size());
    }
    @GetMapping("/getCountByDept")
    public R getCountByDept() {
        List<ContractManage> list=contractMangeService.getContractByDept();
        return R.ok(list, list.size());
    }
    @GetMapping("/getCountByFactory")
    public R getCountByFactory() {
        List<ContractManage> list=contractMangeService.getContractByFactory();
        return R.ok(list, list.size());
    }
    @GetMapping("/getCountByType")
    public R getCountByType() {
        List<ContractManage> list=contractMangeService.getContractByType();
        return R.ok(list, list.size());
    }
    @GetMapping("/getCountByNode")
    public R getCountByNode() {
        List<ContractManage> list=contractMangeService.getContractByNode();
        return R.ok(list, list.size());
    }
    @GetMapping("/getContract")
    public R list(Page page, ContractManage contractManage) {
        EntfrmUser user= SecurityUtil.getUser();
        if(contractManage.getUserId().equals(user.getUserName())){
            Dept dept=deptService.selectDeptById(user.getDeptId());
            if(dept.getCode().equals("01")){
                  if (!contractManage.getSelDepts().equals("")||contractManage.getSelDepts().length()>0){
                        List<String> deptList= Arrays.asList(contractManage.getSelDepts().split(","));
                        contractManage.setSelDept(deptList);
                  }else{
                      contractManage.setSelDept(new ArrayList<>());
                  }
            }else{
                contractManage.setDeptId(dept.getCode());
                contractManage.setSelDept(new ArrayList<>());
            }
            IPage<ContractManage> contractManageIPage = contractMangeService.page(page, getQueryWrapper(contractManage));
            return R.ok(contractManageIPage.getRecords(), contractManageIPage.getTotal());
        }else{
            return R.ok(null, 0);
        }


    }
    @GetMapping("/getContractPlan")
    public R list(Page page, ContractPlan contractPlan) {
        IPage<ContractPlan> ContractPlanIPage = contractPlanService.page(page, getQueryWrapper(contractPlan));
        return R.ok(ContractPlanIPage.getRecords(), ContractPlanIPage.getTotal());
    }
    @GetMapping("/getContractDetail")
    public R list( ContractDetail contractDetail) {
//        IPage<ContractPlan> ContractPlanIPage = contractPlanService.page(page, getQueryWrapper(contractPlan));
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet = null;
        List<ContractDetail> contractDetailList=new ArrayList<>();
        try {
            connection = getConnectionSrm();
            String sql = "SELECT  BP.SN,BP.ProjectName,BP.Currency,BP.PEDisplayName,VP.MaterialCode,VP.MaterialName,VP.Spec,VP.Unit,VP.Qty,VP.Remark,vp.SupplierName,vp.price,vp.taxRate,vp.AwardQty  FROM  BP_Project_M  bp,V_BP_Award vp  where   vp.ProjectTaskID=bp.TaskID AND   bp.sn='"+contractDetail.getSN()+"'AND  BP.ProjectStep='end'";

            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                ContractDetail contractDetail1=new ContractDetail();
               contractDetail1.setSN(resultSet.getString(1));
               contractDetail1.setProjectName(resultSet.getString(2));
                contractDetail1.setCurrency(resultSet.getString(3));
                contractDetail1.setPEDisplayName(resultSet.getString(4));
                contractDetail1.setMaterialCode(resultSet.getString(5));
                contractDetail1.setMaterialName(resultSet.getString(6));
                contractDetail1.setSpec(resultSet.getString(7));
                contractDetail1.setUnit(resultSet.getString(8));
                contractDetail1.setQTY(resultSet.getString(9));
                contractDetail1.setRemark(resultSet.getString(10));
                contractDetail1.setSupplierName(resultSet.getString(11));
                contractDetail1.setPrice(resultSet.getString(12));
                contractDetail1.setTaxRate(resultSet.getString(13));
                contractDetail1.setAwardQty(resultSet.getString(14));
                contractDetailList.add(contractDetail1);
            }
        }catch (Exception e){
            e.printStackTrace();

        }finally {
            try {
                if(resultSet != null){
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(statement != null){
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if(connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return R.ok(contractDetailList, contractDetailList.size());
    }
    public static Connection getConnectionSrm() throws ClassNotFoundException, SQLException {
        String driverClass= GlobalConfig.sqlServerDriver();
        String url=GlobalConfig.dataSouceUrlSrm();
        String user=GlobalConfig.bpmName();
        String password=GlobalConfig.bpmPassword();
        Class.forName(driverClass);
        Connection conn = DriverManager.getConnection(url,user,password);
        return conn;
    }
}
